package com.example.demo.netty.socket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class MyMessageEncoder extends MessageToByteEncoder<String> {

    private final Charset charset;

    public MyMessageEncoder(Charset charset) {
        this.charset = ObjectUtil.checkNotNull(charset, "charset");
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String message, ByteBuf byteBuf){
        log.info("send message to client! message:{}",message);
        byte[] content = message.getBytes(charset);
        byteBuf.writeInt(content.length);
        byteBuf.writeBytes(content);
    }
}
